/*
 * Powered By [rapid-framework]
 * Csdn Code: generate simple CRUD code in single table.
 * Since 2015 - 2017
 */

BUI.use('common/page');
BUI.use(['common/search', 'bui/overlay', 'bui/grid', 'bui/data', 'bui/form'],
    function (Search, Overlay, Grid, Data, Form) {
      var productConditionEnum = {
        '0': '货款金额 ',
        '1': '货款期限',
        '2': '货款类型',
        '2': 'APP描述'
      };
      // 查询表单
      var form = new Form.Form({
        srcNode: '#searchForm'
      }).render();
      // 定义表头
      columns = [
        {
          title: '主键',
          dataIndex: 'productConditionId',
          visible: false
        },
        {
          title: '产口名称',
          dataIndex: 'productName',
          elCls: 'center',
          width: 180,
          editor: {
            xtype: 'text',
            rules: {
              required: [true, '产口名称不能为空!']
            }
          }
        },
        {
          title: '筛选分类',
          dataIndex: 'conditionType',
          elCls: 'center',
          width: 120,
          editor: {
            xtype: 'select',
            items: productConditionEnum,
            rules: {
              required: [true, '筛选分类不能为空!']
            }
          },
          renderer: BUI.Grid.Format
          .enumRenderer(productConditionEnum)
        },
        {
          title: '筛选值',
          dataIndex: 'conditionValue',
          elCls: 'center',
          width: 320,
          editor: {
            xtype: 'text',
            rules: {
              required: [true, '筛选值不能为空!']
            }
          }
        },
        {
          title: '产品ID',
          dataIndex: 'productId',
          visible: false
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          elCls: 'center',
          width: 150,
          editor: {
            xtype: 'date',
            datePicker: {
              showTime: true
            },
            rules: {
              required: [true, '最后创建时间不能为空!']
            }
          },
          renderer: BUI.Grid.Format.datetimeRenderer
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          elCls: 'center',
          width: 150,
          editor: {
            xtype: 'date',
            datePicker: {
              showTime: true
            },
            rules: {
              required: [true, '最后更新时间不能为空!']
            }
          },
          renderer: BUI.Grid.Format.datetimeRenderer
        },
        {
          title: '操作',
          elCls: 'center',
          width: 100,
          renderer: function (value, obj) {
            return '<span class="grid-command btn-edit">编辑</span>';
          }
        }];
      // 行编辑
      var editing = new Grid.Plugins.RowEditing({
            triggerCls: 'btn-edit',
            triggerSelected: false

          }),
          // 获取数据
          store = new BUI.Data.Store({
            url: 'listProductCondition?field=createTime&direction=desc',
            pageSize: 20,
            autoLoad: true,
            remoteSort: true
          });
      // 获取表格对象
      gridCfg = Search.createGridCfg(columns, {
        plugins: [editing, Grid.Plugins.CheckSelection],
        tbar: { // 添加、删除
          items: [{
            btnCls: 'button button-small',
            text: '<i class="icon-plus"></i>添加',
            listeners: {
              'click': addFunction
            }
          }, {
            btnCls: 'button button-small',
            text: '<i class="icon-refresh"></i>刷新',
            listeners: {
              'click': refreshFunction
            }
          }, {
            btnCls: 'button button-small',
            text: '<i class="icon-remove"></i>删除',
            listeners: {
              'click': delFunction
            }
          }]
        },
      });
      // 触发编辑
      editing.on('editorshow', function (ev) {
        var editor = editing.get('curEditor');
        editor.set('errorAlign', {
          points: ['br', 'tr'],
          offset: [0, 10]
        });
      });
      // 编辑提交
      editing.on('accept', function (ev) {
        var record = editing.get('record');
        // console.log(JSON.stringify(record));
        if (record.hasOwnProperty("b")) {
          delete record["b"];
        }
        if (record.hasOwnProperty("")) {
          delete record[""];
        }
        if (record.hasOwnProperty("_")) {
          delete record["_"];
        }
        if (record.hasOwnProperty("createTime")) {
          delete record["createTime"];
        }
        if (record.hasOwnProperty("updateTime")) {
          delete record["updateTime"];
        }
        var saveUrl = record["productConditionId"] === ""
            ? 'saveProductCondition'
            : 'updateProductCondition';
        var requestType = record["productConditionId"] === "" ? 'POST' : 'PUT';
        jQuery.ajax({
          type: requestType,
          url: saveUrl,
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(record),
          complete: function (data) {
            if (data.responseText == "success") { // 删除成功
              search.load();
            } else { // 删除失败
              BUI.Message.Alert('保存失败！');
            }
          }
        });
      });

      // 添加记录
      function addFunction() {
        var newData = {
          'conditionType': ''
        };
        store.addAt(newData, 0);
        editing.edit(newData, 'conditionType'); // 添加记录后，直接编辑
      }

      // 删除选中的记录
      function delFunction() {
        var selections = grid.getSelection();
        delItems(selections);
        store.remove(selections);
      }

      // 刷新
      function refreshFunction() {
        search.load();
      }

      // 删除
      function delItems(items) {
        var ids = "";
        BUI.each(items, function (item) {
          ids += item.productConditionId + ",";
        });
        if (ids.length) {
          BUI.Message.Confirm('确认要删除选中的记录么？', function () {
            jQuery.ajax({
              type: 'DELETE',
              url: 'removeProductCondition?ids=' + ids,
              dataType: 'json',
              data: {
                'ids': ids
              },
              complete: function (data) {
                if (data.responseText == "success") { // 删除成功
                  search.load();
                } else { // 删除失败
                  BUI.Message.Alert('删除失败！');
                }
              }
            });
          }, 'question');
        }
      }

      // 查询
      search = new Search({
        store: store,
        autoSearch: true,
        gridCfg: gridCfg
      });
      grid = search.get('grid');
    });